package com.kming.crypto.algorithm;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * RSA加解密
 * 2022/5/13 9:24
 */
@Slf4j
public class RSA implements Algorithm{
    private final cn.hutool.crypto.asymmetric.RSA rsa;

    public RSA(String privateKey, String publicKey) {
        this.rsa = new cn.hutool.crypto.asymmetric.RSA(privateKey, publicKey);
    }

    @Override
    public InputStream decrypt(String base64Str) {
        byte[] bytes = rsa.decrypt(base64Str, KeyType.PrivateKey);
        log.info("解密前[{}],解密后[{}]", base64Str, new String(bytes));
        return IoUtil.toStream(bytes);
    }

    @Override
    public String encrypt(Object data) {
        String body = JSONUtil.toJsonStr(data);
        String encryptBody = rsa.encryptBase64(body, KeyType.PrivateKey);
        log.info("加密前[{}],加密后[{}]", body, encryptBody);
        return encryptBody;
    }

}
